package git.soulbgm.common.deserializer;

import cn.hutool.core.text.CharSequenceUtil;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import org.apache.commons.lang3.time.DateUtils;

import java.io.IOException;
import java.text.ParseException;
import java.util.Date;

/**
 * 自定义日期反序列化程序
 *
 * @author SoulBGM
 * @date 2024-07-06
 */
public class CustomDateDeserializer extends JsonDeserializer<Date> {

    private final static String[] DATE_FORMATS = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    @Override
    public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        String dateStr = p.getText();
        try {
            if (CharSequenceUtil.isBlank(dateStr)) {
                return null;
            }
            return DateUtils.parseDate(dateStr, DATE_FORMATS);
        } catch (ParseException e) {
            throw new IllegalArgumentException("无效的日期格式。无法解析日期: " + dateStr);
        }
    }

}
